package jnpf.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.thememange.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.*;

import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;

import java.io.IOException;

import org.springframework.transaction.annotation.Transactional;

/**
 * themeMange
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-09
 */
@Slf4j
@RestController
@Tag(name = "themeMange" , description = "example")
@RequestMapping("/api/example/ThemeMange")
public class ThemeMangeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ThemeMangeService themeMangeService;
    @Autowired
    private TagService tagService;



    /**
    * 列表
    *
    * @param themeMangePagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ThemeMangePagination themeMangePagination)throws IOException{
        List<ThemeMangeEntity> list= themeMangeService.getList(themeMangePagination);
        List<Map<String, Object>> realList=new ArrayList<>();

        // 收集所有标签ID
        Set<String> tagIds = new HashSet<>();
        for (ThemeMangeEntity entity : list) {
            if (StringUtil.isNotEmpty(entity.getThemeTag())) {
                List<String> ids = JsonUtil.getJsonToList(entity.getThemeTag(), String.class);
                tagIds.addAll(ids);
            }
        }

        // 批量查询标签名称
        Map<String, String> tagNameMap = new HashMap<>();
        if (!tagIds.isEmpty()) {
            List<TagEntity> tags = tagService.lambdaQuery()
                    .in(TagEntity::getId, tagIds)
                    .list();
            tags.forEach(tag -> tagNameMap.put(tag.getId(), tag.getName()));
        }

        for (ThemeMangeEntity entity : list) {
            Map<String, Object> themeMangeMap=JsonUtil.entityToMap(entity);
            themeMangeMap.put("id", themeMangeMap.get("id"));

            // 处理标签名称
            if (StringUtil.isNotEmpty(entity.getThemeTag())) {
                List<String> tagIdsList = JsonUtil.getJsonToList(entity.getThemeTag(), String.class);
                List<Map<String, String>> tagList = new ArrayList<>();
                for (String tagId : tagIdsList) {
                    Map<String, String> tagMap = new HashMap<>();
                    tagMap.put("id", tagId);
                    tagMap.put("name", tagNameMap.getOrDefault(tagId, ""));
                    tagList.add(tagMap);
                }
                themeMangeMap.put("themeTagName", tagList);
            }

            realList.add(themeMangeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, ThemeMangeConstant.getFormData(), ThemeMangeConstant.getColumnData(), themeMangePagination.getModuleId(),false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(themeMangePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
     * 获取主题挂载实体的数量
     */
    @GetMapping("/getEntityCount/{themeId}")
    @Operation(summary = "获取主题下实体的数量")
    public ActionResult getThemeMangeCount(@PathVariable("themeId") String themeId) {
        return themeMangeService.getEntityCount(themeId);
    }
    /**
    * 创建
    *
    * @param themeMangeForm
    * @return
    */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid ThemeMangeForm themeMangeForm) {
        String b = themeMangeService.checkForm(themeMangeForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            themeMangeService.saveOrUpdate(themeMangeForm, null ,true);
        }catch(Exception e){
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }
    /**
    * 编辑
    * @param id
    * @param themeMangeForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid ThemeMangeForm themeMangeForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        themeMangeForm.setId(id);
        if (!isImport) {
            String b =  themeMangeService.checkForm(themeMangeForm,1);
            if (StringUtil.isNotEmpty(b)){
                return ActionResult.fail(b );
            }
        }
        ThemeMangeEntity entity= themeMangeService.getInfo(id);
        if(entity!=null){
            try{
                themeMangeService.saveOrUpdate(themeMangeForm,id,false);
            }catch(Exception e){
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        ThemeMangeEntity entity= themeMangeService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            themeMangeService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        ThemeMangeEntity entity= themeMangeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> themeMangeMap=JsonUtil.entityToMap(entity);
        themeMangeMap.put("id", themeMangeMap.get("id"));
        //副表数据
        //子表数据
        themeMangeMap = generaterSwapUtil.swapDataDetail(themeMangeMap,ThemeMangeConstant.getFormData(),"678315487712510021",false);
        return ActionResult.success(themeMangeMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        ThemeMangeEntity entity= themeMangeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> themeMangeMap=JsonUtil.entityToMap(entity);
        themeMangeMap.put("id", themeMangeMap.get("id"));
        //副表数据
        //子表数据
        themeMangeMap = generaterSwapUtil.swapDataForm(themeMangeMap,ThemeMangeConstant.getFormData(),ThemeMangeConstant.TABLEFIELDKEY,ThemeMangeConstant.TABLERENAMES);
        return ActionResult.success(themeMangeMap);
    }

}
